#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
检查客服状态和会话信息
"""

import os
import sys
import logging
import requests
from dotenv import load_dotenv

sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from config.settings import settings
from services.wx_api import WeChatAPI

logging.basicConfig(level=logging.INFO)

def check_customer_service_status():
    print("🔍 检查客服状态和会话信息...")
    
    load_dotenv()
    os.environ['WX_CORPID'] = settings.WX_CORPID
    os.environ['WX_CORPSECRET'] = settings.WX_CORPSECRET
    
    wx_api = WeChatAPI()
    access_token = wx_api.get_access_token()
    if not access_token:
        print("❌ 无法获取access_token")
        return
    
    print(f"✅ access_token: {access_token[:20]}***")
    
    # 检查客服会话状态
    print("\n💬 检查客服会话状态...")
    open_kfid = settings.OPEN_KF_ID
    external_userid = "wmtI2SEAAAvOQbOUmj28OCNdTYqYIaYw"
    
    # 获取会话状态
    url = "https://qyapi.weixin.qq.com/cgi-bin/kf/service_state/get"
    params = {
        'access_token': access_token,
        'external_userid': external_userid,
        'open_kfid': open_kfid
    }
    
    try:
        resp = requests.get(url, params=params, timeout=10)
        print(f"状态码: {resp.status_code}")
        print(f"响应: {resp.text}")
    except Exception as e:
        print(f"请求异常: {str(e)}")
    
    # 检查客服接待状态
    print("\n👥 检查客服接待状态...")
    url = "https://qyapi.weixin.qq.com/cgi-bin/kf/service_state/trans"
    params = {
        'access_token': access_token,
        'external_userid': external_userid,
        'open_kfid': open_kfid,
        'servicer_userid': 'LiXingChen'
    }
    
    try:
        resp = requests.get(url, params=params, timeout=10)
        print(f"状态码: {resp.status_code}")
        print(f"响应: {resp.text}")
    except Exception as e:
        print(f"请求异常: {str(e)}")
    
    print("\n📋 可能的问题和解决方案:")
    print("1. IP白名单问题:")
    print("   - 需要在企业微信管理后台设置IP白名单")
    print("   - 或者使用企业微信提供的API调试工具")
    print("2. 客服人员状态:")
    print("   - 确保客服人员在线")
    print("   - 确保客服人员开启了接待功能")
    print("3. 会话状态:")
    print("   - 确保会话状态正确")
    print("   - 检查是否有其他会话冲突")
    
    print("\n🎯 检查完成!")

if __name__ == "__main__":
    check_customer_service_status() 